package com.accp.Interceptor;


import com.accp.common.AjaxRtn;
import com.accp.util.RedisUtil;
import com.accp.util.StringUtil;
import com.accp.util.WebUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    //这个方法是在访问接口之前执行的，我们只需要在这里写验证登陆状态的业务逻辑，就可以在用户调用指定接口之前验证登陆状态了
    @ResponseBody
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userNo = request.getHeader("userId");
        String token = request.getHeader("token");
        if (StringUtil.isNotNullOrEmpty(userNo) && StringUtil.isNotNullOrEmpty(token)) {
            String ret = RedisUtil.get(userNo)+"";
            if (ret != null && ret.equals(token)) {
                return true;
            }
        }
        WebUtil.outJson(response, new AjaxRtn(false,"token失效重新登陆"));
        return false;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}